package com.gitee.ricesugar.service.impl;

import cn.hutool.core.util.IdUtil;
import com.gitee.ricesugar.controller.request.BaseRequest;
import com.gitee.ricesugar.entity.Admin;
import com.gitee.ricesugar.exception.ServiceException;
import com.gitee.ricesugar.mapper.AdminMapper;
import com.gitee.ricesugar.service.IAdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AdminService implements IAdminService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public void add(Admin obj) {
        List<Admin> admins = adminMapper.listByUsername(obj.getUsername());
        if(!admins.isEmpty()){
            throw new ServiceException("用户名已存在");
        }
        int uid = Math.abs(IdUtil.fastSimpleUUID().hashCode());
        obj.setUid(Integer.toString(uid));
        adminMapper.add(obj);
    }

    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Admin> obj = adminMapper.listByCondition(baseRequest);
        return new PageInfo<>(obj);
    }

    @Override
    public Admin getByUid(String uid) {
        return adminMapper.getByUid(uid);
    }

    @Override
    public void update(Admin obj) {
        Date date = new Date();
        obj.setUpdateDate(date);
        adminMapper.updateByUid(obj);
    }

    @Override
    public void deleteByUid(String uid) {
        adminMapper.deleteByUid(uid);
    }
}
